package br.com.ravi.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.ravi.vo.UserVO;

//@WebFilter(urlPatterns="*.jsp")
public class LoggedUserFilter implements Filter{
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        String requestURI = httpServletRequest.getRequestURL().toString();
        if (requestURI != null && (requestURI.contains("LoginAction") || requestURI.contains("Login.jsp"))) {
                chain.doFilter(req, resp);
        }
        else {
                UserVO userVO = (UserVO) httpServletRequest.getSession().getAttribute("USUARIOLOGADO");
                if (userVO == null) {
                        HttpServletResponse response = (HttpServletResponse) resp;
                        String contextPath = httpServletRequest.getContextPath();
                        
                        response.setContentType("text/html");
                        response.sendRedirect(contextPath + "/pages/Login.jsp");
                        return;
                }
                else {
                        chain.doFilter(req, resp);
                }
        }               
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}